package org.edu.modules.enroll.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.edu.common.api.vo.Result;
import org.edu.modules.enroll.entity.*;
import org.edu.modules.enroll.service.IVeBaseManageService;
import org.edu.modules.enroll.service.VeBaseBanjiService;
import org.edu.modules.enroll.service.VeBaseGradeService;
import org.edu.modules.enroll.service.VeZsRegistrationService;
import org.edu.modules.enroll.vo.VeZsRegistrationVo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * 学生分班管理
 * @author yhx
 */
@Api(tags = "学生分班管理")
@RestController
@RequestMapping("enroll/divideClassMng")
public class DivideClassMngController {

    @Resource
    private VeBaseGradeService veBaseGradeService;

    @Resource
    private VeZsRegistrationService veZsRegistrationService;

    @Resource
    private VeBaseBanjiService veBaseBanjiService;

    @Resource
    private IVeBaseManageService iVeBaseManageService;

    @ApiOperation(value = "获取年级")
    @PostMapping(value = "/getGrade")
    public Result<?> getGrade() {
        List<VeBaseGrade> list = veBaseGradeService.list();//2021.9.1
//        ---------------------（林彬辉）
//        BasicResponseBO<List<VeBaseGrade>> listBasicResponseBO = iVeBaseManageService.getGradeAll();
//        List<VeBaseGrade> list = listBasicResponseBO.getResult();
//        -------------------------
        return Result.OK(list);


    }

    @ApiOperation(value = "获取班级")
    @PostMapping(value = "/getClazz")
    public Result<?> getClazz(@ApiParam("年级ID") @RequestParam("gradeId") Long gradeId,
                              @ApiParam("专业ID") @RequestParam("specialtyId") Long specialtyId) {

//        QueryWrapper<VeBaseBanji> wrapper = new QueryWrapper<>();
//        wrapper.eq("gradeId", gradeId);
//        wrapper.eq("specId", specialtyId);

//        List<VeBaseBanji> list = veBaseBanjiService.list(wrapper);
        //传入0视为null
        if(specialtyId==0){
            specialtyId = null;
        }
        BasicResponseBO<List<VeBaseBanji>> b = new BasicResponseBO<>();
        List<VeBaseBanji> list = null;
        //使用接口获取数据(林彬辉）-------------------------------
        if (gradeId == null && specialtyId == null){
            list = veBaseBanjiService.list();//2021.9.1
//            b = iVeBaseManageService.getBanjiAll();
//            list = b.getResult();
        }else if (gradeId != null && specialtyId != null){
//            BasicResponseBO<List<VeBaseBanji>> bByGradeId = iVeBaseManageService.getBanjiByGradeId(gradeId);
//            BasicResponseBO<List<VeBaseBanji>> bSpecialtyId = iVeBaseManageService.getBanjiBySpecId(specialtyId);
//            //获取交集集合
//            list = receiveCollectionList(bByGradeId.getResult(),bSpecialtyId.getResult());
            QueryWrapper<VeBaseBanji> banjiQueryWrapper = new QueryWrapper<>();
            banjiQueryWrapper.eq("grade_id",gradeId);
            List<VeBaseBanji> list1 = veBaseBanjiService.list(banjiQueryWrapper);
            QueryWrapper<VeBaseBanji> specialtyQueryWrapper = new QueryWrapper<>();
            specialtyQueryWrapper.eq("spec_id",specialtyId);
            List<VeBaseBanji> list2 = veBaseBanjiService.list(specialtyQueryWrapper);
            //获取交集集合
            list = receiveCollectionList(list1,list2);//2021.9.1
             System.out.println(list.size()+"交集"+list);
        }else if (gradeId == null && specialtyId != null){
//            BasicResponseBO<List<VeBaseBanji>> bSpecialtyId = iVeBaseManageService.getBanjiBySpecId(specialtyId);
//            list = bSpecialtyId.getResult();
            QueryWrapper<VeBaseBanji> specialtyQueryWrapper = new QueryWrapper<>();
            specialtyQueryWrapper.eq("spec_id",specialtyId);
            list = veBaseBanjiService.list(specialtyQueryWrapper);//2021.9.1
        }else if (gradeId != null && specialtyId == null){
//            BasicResponseBO<List<VeBaseBanji>> bByGradeId = iVeBaseManageService.getBanjiByGradeId(gradeId);
//            list = bByGradeId.getResult();
            QueryWrapper<VeBaseBanji> banjiQueryWrapper = new QueryWrapper<>();
            banjiQueryWrapper.eq("grade_id",gradeId);
            list = veBaseBanjiService.list(banjiQueryWrapper);//2021.9.1
        }

        System.out.println(list.size()+"班级信息"+list);
//        ----------------------------
        return Result.OK(list);

    }

//    public static void main(String[] args) {
//
//    }
    @ApiOperation(value = "获取未分班学生集合")
    @PostMapping(value = "/select")
    public Result<?> getStuListOfNoDivideClass(@ApiParam("年级ID") @RequestParam("gradeId") Long gradeId,
                                               @ApiParam("专业部ID") @RequestParam("facultyId") Long facultyId,
                                               @ApiParam("专业ID") @RequestParam("specialtyId") Long specialtyId,
                                               @ApiParam("关键词") @RequestParam("keyword") String keyword,
                                               @ApiParam("查询条件") @RequestParam("condit") String condit,
                                               @ApiParam("当前页") @RequestParam("currentPage") Integer currentPage,
                                               @ApiParam("条数") @RequestParam("pageSize") Integer pageSize) {

        if (gradeId == 0) {
            gradeId = null;
        }
        if (facultyId == 0) {
            facultyId = null;
        }
        if (specialtyId == 0) {
            specialtyId = null;
        }

        //页码条件
        Integer current = (currentPage - 1) * pageSize;
        //根据页码查询数据
        List<VeZsRegistrationVo> list = veZsRegistrationService.getStuOfNoDivideClass(gradeId, facultyId, specialtyId, keyword, condit, current, pageSize);
        //获取年级名称
//        BasicResponseBO<List<VeBaseGrade>> listBasicResponseBO = iVeBaseManageService.getGradeAll();
//        List<VeBaseGrade> gradeList = listBasicResponseBO.getResult();
        List<VeBaseGrade> gradeList = veBaseGradeService.list();//2021.9.1
        for (VeZsRegistrationVo v : list){
            for (VeBaseGrade grade : gradeList){
                if (v.getGradeId() == grade.getId()){
                    v.setNjmc(grade.getNjmc());
                    break;
                }
            }

        }

        //条件构造器
        QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();
        wrapper.eq("isCheck", 1);
        wrapper.eq("isAdmit", 1);
        wrapper.eq("isReport", 0);
        wrapper.isNull("classId");

        if (gradeId != null) {
            wrapper.eq("gradeId", gradeId);
        }

        if (facultyId != null) {
            wrapper.eq("falId", facultyId);
        }

        if (specialtyId != null) {
            wrapper.eq("specId", specialtyId);
        }

        if (condit != null && keyword != null && (!keyword.trim().equals(""))) {
            wrapper.like(condit, keyword);
        }

        //查询总数
        Integer count = veZsRegistrationService.list(wrapper).size();

        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("count", count);

        return Result.OK(map);
    }

    @ApiOperation(value = "获取班级人数、已分班学生集合")
    @PostMapping(value = "/getClazzInfo")
    public Result<?> getStuListOfDivideClass(@ApiParam("班级ID") @RequestParam("clazzId") Long clazzId,
                                             @ApiParam("当前页") @RequestParam("currentPage") Integer currentPage,
                                             @ApiParam("条数") @RequestParam("pageSize") Integer pageSize) {


        //获取班级对象
        VeBaseBanji veBaseBanji = veBaseBanjiService.getById(clazzId);//2021.9.1
//        -----------------(林彬辉）
//        BasicResponseBO<VeBaseBanji> listBasicResponseBO = iVeBaseManageService.getBanjiById(clazzId);
//        VeBaseBanji veBaseBanji = listBasicResponseBO.getResult();

//        -------------------
//                System.out.println(veBaseBanji);

        //页码条件
        Integer current = (currentPage - 1) * pageSize;
        //根据页码查询数据
        List<VeZsRegistrationVo> list = veZsRegistrationService.getStuOfDivideByClazzId(clazzId, current, pageSize);
        //获取年级名称
//        BasicResponseBO<List<VeBaseGrade>> gradeAll= iVeBaseManageService.getGradeAll();
//        List<VeBaseGrade> gradeList = gradeAll.getResult();
        List<VeBaseGrade> gradeList = veBaseGradeService.list();
        for (VeZsRegistrationVo v : list){
            for (VeBaseGrade grade : gradeList){
                if (v.getGradeId() == grade.getId()){
                    v.setNjmc(grade.getNjmc());
                    break;
                }
            }

        }

        //条件构造器
        QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();
        wrapper.eq("isCheck", 1);
        wrapper.eq("isAdmit", 1);
        wrapper.eq("isReport", 0);
        wrapper.eq("classId", clazzId);

        Integer count = veZsRegistrationService.list(wrapper).size();

        HashMap<String, Object> map = new HashMap<>();
        map.put("clazz", veBaseBanji);
        map.put("count", count);
        map.put("list", list);
        return Result.OK(map);

    }

    @ApiOperation(value = "分班")
    @PostMapping(value = "/divideClass")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> divideClass(@ApiParam("班级ID") @RequestParam("clazzId") Long clazzId,
                                             @ApiParam("ID字符串") @RequestParam("ids") String ids) {

        //新增的男女生人数
        Integer manNum = 0;
        Integer womanNum = 0;

        String[] split = ids.split(",");

        //给学生信息添加班级ID
        List<VeZsRegistration> list = new ArrayList<>();

        for(String sp : split){

            Long id = Long.parseLong(sp);
            //设置修改的条件对象
            VeZsRegistration veZsRegistration = new VeZsRegistration();
            veZsRegistration.setId(id);
            veZsRegistration.setClassId(clazzId);
            list.add(veZsRegistration);

            QueryWrapper<VeZsRegistration> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",id);
            //获取学生对象
            VeZsRegistration one = veZsRegistrationService.getOne(queryWrapper);
            String xbm = one.getXbm();
            //根据性别 增加对应人数
            if(xbm.equals("1")){
                //男生人数增加
                manNum++;
            }else if(xbm.equals("2")){
                //女生人数增加
                womanNum++;
            }

        }
        //给相应条件的学生添加班级ID
        veZsRegistrationService.updateBatchById(list);

        //获取男女生人数、总人数
        QueryWrapper<VeBaseBanji> qw = new QueryWrapper<>();
        qw.eq("id",clazzId);
        VeBaseBanji one = veBaseBanjiService.getOne(qw);
//        ----------------------------林彬辉
//        BasicResponseBO<VeBaseBanji> listBasicResponseBO = iVeBaseManageService.getBanjiById(clazzId);
//        VeBaseBanji one = listBasicResponseBO.getResult();
//        ----------------------------------------
//        ---------------------编辑班级信息接口不可用暂不能实现，林彬辉
        //将班级表中的男女生人数改变
//        UpdateWrapper<VeBaseBanji> wrapper = new UpdateWrapper<>();
//        wrapper.eq("id",clazzId);
//        wrapper.set("NANSRS", one.getNansrs()+manNum);
//        wrapper.set("NVSRS", one.getNvsrs()+womanNum);

        //修改班级表中 男女生的人数
        int res = veBaseBanjiService.updateNanAndNvrs(clazzId,one.getNansrs()+manNum,one.getNvsrs()+womanNum);
//        veBaseBanjiService.update(wrapper);
        if (res<=0){
            return Result.error("修改班级男女生人数失败");
        }
//-------------------------------
        return Result.OK("分班成功！");
    }

    @ApiOperation(value = "退班")
    @PostMapping(value = "/dropClass")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> dropClass(@ApiParam("班级ID") @RequestParam("clazzId") Long clazzId,
                               @ApiParam("ID字符串") @RequestParam("ids") String ids) {

        //减少的男女生人数
        Integer manNum = 0;
        Integer womanNum = 0;

        //给学生信息班级ID置空
        String[] split = ids.split(",");

        for(String sp : split){

            Integer id = Integer.parseInt(sp);
            //设置修改的条件对象
            UpdateWrapper<VeZsRegistration> qw = new UpdateWrapper<>();
            qw.eq("id",id);
            qw.set("classId",null);

            //退班
            veZsRegistrationService.update(qw);

            QueryWrapper<VeZsRegistration> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",id);
            //获取学生对象
            VeZsRegistration one = veZsRegistrationService.getOne(queryWrapper);
            String xbm = one.getXbm();
            //根据性别 增加对应人数
            if(xbm.equals("1")){
                //男生人数增加
                manNum++;
            }else if(xbm.equals("2")){
                //女生人数增加
                womanNum++;
            }

        }

        //获取男女生人数、总人数
        QueryWrapper<VeBaseBanji> qw = new QueryWrapper<>();
        qw.eq("id",clazzId);
        VeBaseBanji one = veBaseBanjiService.getOne(qw);//2021.9.1
//        BasicResponseBO<VeBaseBanji> listBasicResponseBO = iVeBaseManageService.getBanjiById(clazzId);
//        VeBaseBanji one = listBasicResponseBO.getResult();
        //将班级表中的男女生人数改变
//        UpdateWrapper<VeBaseBanji> wrapper = new UpdateWrapper<>();
//        wrapper.eq("id",clazzId);
//
//        if(one.getNansrs()-manNum >= 0){
//            wrapper.set("NANSRS", one.getNansrs()-manNum);
//        }
//
//        if(one.getNvsrs()-womanNum >= 0){
//            wrapper.set("NVSRS", one.getNvsrs()-womanNum);
//        }

        //修改班级表中 男女生的人数
        int res = veBaseBanjiService.updateNanAndNvrs(clazzId,one.getNansrs()-manNum,one.getNvsrs()-womanNum);
//        veBaseBanjiService.update(wrapper);
        if (res<=0){
            return Result.error("修改班级男女生人数失败");
        }

        return Result.OK("退班成功！");
    }


    //取集合交集（林彬辉）
    public static List receiveCollectionList(List firstArrayList, List secondArrayList) {
        List bigList = null;
        List smallList = null;
        if (firstArrayList.size() >= secondArrayList.size()){
            bigList = firstArrayList;
            smallList = secondArrayList;
        }else {
            bigList = secondArrayList;
            smallList = firstArrayList;
        }
        List resultList = new ArrayList();

        LinkedList result = new LinkedList(bigList);// 大集合用linkedlist

        HashSet othHash = new HashSet(smallList);// 小集合用hashset

        Iterator iter = result.iterator();// 采用Iterator迭代器进行数据的操作

        while(iter.hasNext()) {
            if(!othHash.contains(iter.next())) {
                iter.remove();

            }

        }

        resultList = new ArrayList(result);

        return resultList;

    }




}
